package com.ware.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.ware.dao.User;
import com.ware.util.AjaxResult;

public class UserController extends BaseController{
	

	public void info() {
//		String id = this.getPara("id", "");
//		
//		if (StrKit.notBlank("id")) {
//			this.setAttr("id", id);
//		}
//		
		this.render("register1.ftl");
	}
	
	public void edit(){
		AjaxResult result = new AjaxResult(1);
		Gson gson = new Gson();
		try {
			Map<String, Object> user = gson.fromJson(this.getPara("user",""),new TypeToken<Map<String, Object>>(){}.getType());
			user.remove("re_password");
			if(user.containsKey("id")){
				
				this.render("index.ftl");
			}else{
				String sql = "select * from user where name=?";
				User u = User.dao.findFirst(sql, user.get("name"));
				if(u==null){					
					User.dao.clear().setAttrs(user).save();
				}else{
					result.addError("该用户已经存在！");
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.addError(e.getMessage());
		}
		this.renderJson(result.toJson());
	}
	
	public void getUser(){
		String id = this.getPara("id","");
		if(StrKit.notBlank(id)){
			this.renderJson(User.dao.findById(id).toJson());
		}else{
			this.renderJson("");
		}
	}
	
	public void getUsers(){
		String sql = "select * from user ";
		List<User> users = User.dao.find(sql);
		this.renderJson(JsonKit.listToJson(users, 2));
	}
}
